<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocet</title>
</head>
<body>
<h1>Chat Room</h1>

<input type="text" id="sendTxt">
<button id="sendBtn">发送</button>

<script>
    //建立连接
    let webSocket = new WebSocket('ws://localhost:8001/');

    //开启连接
    webSocket.onopen = function () {
        console.log('webSocket open');
        //发送信息
        document.getElementById('sendBtn').onclick = function () {
            var text = document.getElementById('sendTxt').value;
            if (text) {
                webSocket.send(text);
            }
        };
    };

    //关闭连接
    webSocket.onclose = function () {
        console.log('webSocket close');
    };

    //拿到返回
    webSocket.onmessage = function (e) {
        console.log(e.data);
        var message=JSON.parse(e.data);
        showMessage(message.data,message.type);
    };

    //辅助函数
    function showMessage(str,type){
        var div=document.createElement('div');
        div.innerHTML=str;
        if(type==='enter'){
            div.style.color='blue';
        }else if(type==='leave'){
            div.style.color='red'
        }
        document.body.appendChild(div);
    }
</script>
</body>
</html>